import React, { useState } from 'react';
import { Alert, Button, Col, Form, Modal, Popover, Row, Segmented, Space, Tabs } from 'antd';
import { iconData, IconTabType } from './iconData';
// @ts-ignore
import { Rule } from 'rc-field-form/es/interface';
import { LabelTooltipType } from 'antd/es/form/FormItemLabel';
import { ProCard, ProForm, ProFormText } from '@ant-design/pro-components';
import { EyeOutlined } from '@ant-design/icons';
import { FORM_CONFIG } from '@/options';
import MyIcon from '@/components/MyIcon';

export type FormProps = {
  name?: string;
  label?: React.ReactNode;
  placeholder?: string | string[];
  rules?: Rule[];
  width?: number | 'sm' | 'md' | 'xl' | 'xs' | 'lg';
  disabled?: boolean;
  /**
   * 图标弹窗设置
   */
  modal?: {
    title?: string;
    width?: string | number;
    buttonLabel?: string;
    alert?: string;
  };
  /**
   * 图标预览
   */
  preview?: boolean;
  tooltip?: LabelTooltipType;
  readonly?: boolean;
};

const IconSelect: React.FC<FormProps> = (props) => {
  const {
    name = 'iconName',
    width = 'sm',
    label = '菜单图标',
    tooltip = '不支持自定义图标代码，请通过点击选择图标按钮获取图标代码。',
    placeholder = '请选择菜单图标',
    // 是否展示预览图标（当图标内容不为空时展示）
    preview = true,
    rules,
    modal = {
      title: '图标列表',
      width: FORM_CONFIG.width,
      buttonLabel: '选择图标',
      alert: '点击列表中的图标即可选择图标代码。',
    },
    readonly = false,
  } = props;
  const form = Form.useFormInstance();
  const iconPreview = form?.getFieldValue(name);

  /**
   * 点击按钮
   * 图标列表弹窗
   */
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [icons, setIcons] = useState<IconTabType[]>();
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const formatIcon = (icons: IconTabType[]) => {
    return icons.map((c) => {
      c.children = (
        <Row
          gutter={[24, 12]}
          style={{
            overflowY: 'auto',
            height: '60vh',
            alignContent: 'flex-start',
          }}
        >
          {c.icons.map((v) => {
            return (
              <Col
                key={v}
                xs={6}
                xl={4}
                xxl={3}
                className="text-center cursor-pointer rounded-lg hover:shadow-lg"
                style={{
                  transition: 'box-shadow 0.3s ease',
                  height: '120px',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                onClick={() => {
                  form?.setFieldValue(name, v);
                  handleCancel();
                }}
              >
                <MyIcon name={v} className="text-[36px] mb-[10px]" />
                <div className="w-full text-[14px]">{v}</div>
              </Col>
            );
          })}
        </Row>
      );
      return c;
    });
  };
  const showModal = () => {
    setIsModalOpen(true);
    setIcons(formatIcon(iconData[0].icons));
  };

  return (
    <>
      <ProForm.Item label={label} tooltip={tooltip}>
        <Space direction="horizontal">
          <ProFormText
            name={name}
            placeholder={placeholder}
            rules={rules}
            width={width}
            noStyle
            disabled
            fieldProps={{
              suffix:
                preview && iconPreview ? (
                  <Popover
                    content={
                      <ProCard title={iconPreview} headerBordered>
                        <div style={{ textAlign: 'center' }}>
                          <MyIcon
                            name={iconPreview}
                            style={{
                              margin: '8px 0 8px',
                              fontSize: '48px',
                            }}
                          />
                        </div>
                      </ProCard>
                    }
                  >
                    <EyeOutlined
                      style={{
                        cursor: 'pointer',
                        color: '#1890ff',
                      }}
                    />
                  </Popover>
                ) : null,
            }}
          />
          {!readonly && (
            <Button type="primary" onClick={showModal} disabled={props.disabled}>
              {modal?.buttonLabel}
            </Button>
          )}
        </Space>
      </ProForm.Item>
      <Modal
        title={modal?.title}
        width={modal?.width}
        destroyOnClose
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {modal?.alert ? (
            <Alert
              type="success"
              closable
              message={
                // <Marquee pauseOnHover gradient={false}>
                modal?.alert
                // </Marquee>
              }
            />
          ) : null}
          <Segmented
            style={{ marginBottom: 8 }}
            onChange={(value) => {
              iconData.forEach((c) => {
                if (c.value === value) {
                  setIcons(formatIcon(c.icons));
                }
              });
            }}
            options={iconData}
          />
        </Space>
        <Tabs items={icons} popupClassName="z-[1500]" />
      </Modal>
    </>
  );
};

export default IconSelect;
